<!-- 老虎机 -->
<template>
  <el-dialog v-if="props.show" :model-value="props.show" :title="'【老虎机】' + data.game_name" :close-on-click-modal="false"
    :close-on-press-escape="false" top="8vh" width="65%" @close="onHideDetails">
    <div v-loading="indexStore.moduleLoading">
      <div class="dialogMaxHeight padding20">
        <el-form :class="props.isDisableUser ? 'disableUser' : ''" ref="ruleFormRef" :model="data" :inline="true"
          :rules="rules" :scroll-to-error="true">
          <form-item title="游戏名称" value="game_name">
            <GameHeaderInfo :game_id="props.checkedItem.game_id" />
          </form-item>
          <form-item title="RTP设定" :pass="true" value="a_slots_backend_echo">
            <el-select v-model="data.a_slots_backend_echo" placeholder="请选择RTP" filterable>
              <el-option v-show="item && item == 200 ? operatorTypeShow : true" v-for="item in data.rtpList"
                :label="item + '%'" :value="item" />
            </el-select>
            <span class="tipsTextRed"> (选择玩家在游戏中的回报率)</span>
          </form-item>
          <!-- JILI游戏才显示 -->
          <form-item title="RTP类型" value="a_slots_rtptype">
            <el-select v-model="data.a_slots_rtptype" placeholder="请选择RTP类型" filterable>
              <el-option v-for="item in RtpType" :label="item.label" :value="item.value"
                v-show="item.value < 4 ? true : false" />
            </el-select>
            <span class="tipsText"> (选择玩家在游戏中的回报率的类型)</span>
          </form-item>
          <form-item v-show="data.a_slots_auto != -1 ? true : false" title="止损止赢开关" value="a_slots_auto">
            <el-radio-group v-model="data.a_slots_auto" size="large">
              <el-radio-button label="开启" :value="0" />
              <el-radio-button label="关闭" :value="1" />
            </el-radio-group>
            <span class="tipsText marginT2">(slot的AUTO附加功能，开启后，玩家在游戏内自动旋转时，可以设定条件，达到输赢条件停止自动旋转)</span>
          </form-item>
          <form-item v-if="!indexStore.is_general_agent" title="游戏wild元素ID" :pass="true" value="a_slots_wildid">
            <el-input-number :min="0" :max="999999999999999" :precision="0" v-model="data.a_slots_wildid"
              placeholder="请输入游戏wild元素ID" clearable controls-position="right" />
            <span class="tipsText">(游戏端的游戏wild元素ID)</span>
          </form-item>
          <form-item v-if="!indexStore.is_general_agent" title="小游戏图标" :pass="true" value="a_slots_scatterid">
            <el-input-number :min="0" :max="999999999999999" :precision="0" v-model="data.a_slots_scatterid"
              placeholder="小游戏图标" clearable controls-position="right" />
            <span class="tipsText ">(游戏中小游戏图标)</span>
          </form-item>
          <form-item v-if="data.a_slots_buy != -1" title="购买小游戏功能" class="flex" :pass="true" value="a_slots_buy">
            <el-radio-group v-model="data.a_slots_buy" size="large">
              <el-radio-button label="关闭" :value="0" />
              <el-radio-button label="开启" :value="1" />
            </el-radio-group>
            <span class="tipsText">(是否开启购买小游戏功能)</span>
          </form-item>
        </el-form>
        <!-- JILI游戏不能新增删除投注金额个数 -->
        <form-item v-if="!data.isPPshow" title="投注金额" value="a_slots_amount" :subtract="data.gameAmountShow"
          @addItem="addPressure">
          <p v-if="!props.showDefault && data.isMaintenance" class="tipsTextRed">*(游戏在维护状态下才能编辑)</p>
          <div class="tipsText width100">(游戏的单押投注额度展示；游戏的总押注=单押额*押注等级（1~10）*游戏线数)</div>
          <div ref="scrollContainer"
            :class="(props.checkedItem.platform == '2' || props.checkedItem.platform == '4') ? 'flex amountBox' : ''">
            <div :class="props.checkedItem.platform == '3' ? 'flex' : ''" class="margin5"
              v-for="(item, index) in data.pressureList" :key="index">
              <div class="flex marginR5">
                <el-input-number class="width200" :disabled="data.isMaintenance || data.isConditions" :min="0.001"
                  :max="99999999999999999999" :precision="3" v-model="item.num" placeholder="请输入基础面额" clearable
                  controls-position="right" @input="setArrMultipleControl" />
                <div v-show="data.gameAmountShow" class="reduce-btn reduce-btn_new marginL5"
                  @click="reducePressure(index)">-</div>
              </div>
              <div class="box-item">
                <div v-for="(second, index) in data.otherLevel" :key="index">
                  {{ item.num }} x 押注等级{{ second }} x 线数{{ data.otherLine }} x 缩小倍数{{ data.client_balance_scale }} =
                  总押注 <span class="mustPass">{{ BigTimes(BigTimes(second, BigTimes(item.num,
                    data.otherLine)), data.client_balance_scale) }}</span>
                </div>
              </div>
            </div>
          </div>
        </form-item>
        <!-- 自有PP游戏---投注金额-->
        <form-item v-else title="PP投注金额" value="a_slots_amount" :subtract="false">
          <p v-if="!props.showDefault && data.isMaintenance" class="tipsTextRed">*(游戏在维护状态下才能编辑)</p>
          <div class="tipsText width100">(游戏的单押投注额度展示；游戏的总押注=单押额*押注等级（1~10）*游戏线数)</div>
          <div ref="scrollContainer" class="amountBox">
            <div class="flex">
              <div class="margin5" v-for="(item, index) in data.pressureList" :key="index">
                <div class="flex marginR5">
                  {{ !index ? '设定下限值：' : '设定上限值：' }}
                  <el-input-number class="width200" :disabled="data.isMaintenance || data.isConditions" :min="0.001"
                    :max="99999999999999999999" :precision="3" v-model="item.num" placeholder="请输入基础面额" clearable
                    controls-position="right" @input="setArrMultipleControl" />
                </div>
              </div>
            </div>
            <div class="flex">
              <div class="marginR5" v-for="(item, index) in data.pressurePPList" :key="index">
                <div class="box-item">
                  <div v-for="(second, index) in data.otherLevel" :key="index">
                    {{ item.num }} x 押注等级{{ second }} x 线数{{ data.otherLine }} = 总押注 <span class="mustPass">{{
                      BigTimes(second, BigTimes(item.num, data.otherLine)) }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </form-item>
        <form-item v-if="props.checkedItem.platform != '3'" title="默认投注金额" value="a_slots_defaultamount">
          <div>
            <p class="flex">
              <span v-if="!props.showDefault && data.isMaintenance" class="tipsTextRed">*(游戏在维护状态下才能编辑)</span>
              <span class="tipsText ">(设置玩家进入游戏时的初始默认投注金额；投注金额=单押额度*押注等级*游戏线数)</span>
            </p>
            <div class="margin5" v-for="(item, index) in data.defaultList" :key="index">
              <div class="flex marginR5">
                单押注额度：<el-select class="marginR20" v-model="data.defaultList[0].num"
                  :disabled="data.isMaintenance || data.isPPshow" placeholder="请选择基础压注面额" filterable>
                  <el-option v-for="item in data.pressureList" :label="item.num" :value="item.num" />
                </el-select>
                押注等级：<el-select v-model="data.defaultList[0].level" :disabled="data.isMaintenance || data.isPPshow"
                  placeholder="请选择基础压注面额" filterable>
                  <el-option v-for="item in data.otherLevel" :label="item" :value="item" />
                </el-select>
              </div>
              <div class="box-item marginT5">
                {{ data.defaultList[0].num }} x 押注等级{{ data.defaultList[0].level }} x 线数{{ data.defaultList[0].line }} x
                缩小倍数{{ data.client_balance_scale }}=
                总押注 <span class="mustPass">{{ BigTimes(BigTimes(BigTimes(item.num,
                  data.defaultList[0].line), data.defaultList[0].level), data.client_balance_scale) }}</span>
              </div>
            </div>
          </div>
        </form-item>
        <form-item title="爆奖倍数控制" value="a_slots_multiplecontrol">
          <div class="flexWrap margin5" v-for="(item, index) in data.multipleControl" :key="index" v-show="item.show">
            【<span class="colorRed marginR2">{{ item.position }}</span>】 档下注：<span class="colorRed">【{{ item.bet }}<span
                v-if="item.position == -1" class="colorRed">~{{ item.maxBet }}</span>】</span>
            倍数下限:
            <el-input-number v-model="item.min" :min="-99999999999999999999" :max="99999999999999999999" :precision="0"
              class="width120 marginR5" placeholder="倍数下限" clearable :controls="false" />
            倍数上限:
            <el-input-number v-model="item.max" :min="0" :max="99999999999999999999" :precision="0"
              class="width120 marginR5" placeholder="倍数上限" clearable :controls="false" />
            <span v-if="!indexStore.is_general_agent">
              开始判定倍数:
              <el-input-number v-model="item.multiple" :min="0" :max="99999999999999999999" :precision="0"
                class="width120 marginR5" placeholder="倍数上限" clearable :controls="false" />
            </span>
          </div>
        </form-item>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer" v-show="!props.isDisableUser">
        <el-button type="info" @click="onHideDetails">取 消</el-button>
        <el-button type="primary" @click="gameSet(ruleFormRef)">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import GameHeaderInfo from '@/components/FormItem/GameHeaderInfo.vue'
import { BigTimeWan, BigTimes, BigDiv } from '@/utils/math'
import { RtpType } from '@/config/eunm'
import { throttle } from '@/utils/index'
import { getOperatorTiger, editTiger, getGameStatus, getBetAmount } from '@/api/game'


import { useStore } from '@/stores/index'
const indexStore = useStore()

const props = defineProps({
  show: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  showDefault: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  isDisableUser: {
    type: Boolean,
    default: () => {
      return false
    }
  },
  checkedItem: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const data = reactive({
  id: 0,
  game_id: 0,
  game_name: '',
  a_slots_backend_echo: 0,
  a_slots_rtptype: 0,
  a_slots_auto: -1,
  a_slots_buy: 0,
  a_slots_wildid: 0,
  a_slots_scatterid: 0,
  a_slots_multipleclose: 0,
  a_slots_buymultiple: 0,
  a_slots_maxwin: 0,
  a_rtp_check: 0,
  a_rtp_control: 0,
  a_slots_poolproportion: 0,
  multipleControl: [] as any[],
  bigControl: [] as any[],
  trial_path: '',
  pressureList: [] as any[],
  defaultList: [] as any[],
  otherLevel: [] as number[],
  highControl: [] as any[],
  whiteList: [] as any[],
  controlList: [] as any[],
  pressurePPList: [] as any[],
  otherLine: 0,
  rtpList: [],
  isMaintenance: false,
  platform: '2',
  gameAmountShow: false,
  isConditions: false,
  client_balance_scale: 1,
  ppa_slots_amount: '',
  isPPshow: false, // 是否是PP游戏
})

watch(
  () => [props.checkedItem, props.show],
  async (value) => {
    if (value[0]) {
      Object.assign(data, props.checkedItem)
    }
    if (value[1]) {
      chooseOperator(props.checkedItem.agent_id, props.checkedItem.game_id)
    }
  },
)

const operatorTypeShow = (!indexStore.is_general_agent || indexStore.userInfo.operator_type) ? true : false

// 选择运营商
const chooseOperator = async (id: number, game_id: number) => {
  let res = await getOperatorTiger({
    agent_id: id, game_id: game_id
  })
  res.data.isMaintenance = false
  // 总控的时候放开
  if ((res.data.game_id == 10223 || res.data.game_id == 10051) && indexStore.is_general_agent) {
    data.isConditions = true
  } else {
    data.isConditions = false
  }
  // 处理压注缩小倍数
  res.data.defaultList.forEach((item: any) => {
    item.num = BigDiv(item.num, data.client_balance_scale)
  })
  res.data.pressureList.forEach((item: any) => {
    item.num = BigDiv(item.num, data.client_balance_scale)
  })
  Object.assign(data, res.data)
  getGameInfo(props.checkedItem)
  setArrMultipleControl()
}

// 游戏在维护状态下才能编辑
const getGameInfo = async (row: any) => {
  let res = await getGameStatus({
    agent_id: row.agent_id,
    game_id: row.game_id
  })
  if (res.data.status) {
    data.isMaintenance = true
  } else {
    data.isMaintenance = false
  }
  // 控制--投注按钮是否显示隐藏
  if (!data.isMaintenance && !props.isDisableUser && (props.checkedItem.platform != '3' || !indexStore.is_general_agent)) {
    data.gameAmountShow = true
  } else {
    data.gameAmountShow = false
  }
}

// 设置
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<typeof data>>({
  game_name: [{ required: true, message: '请输入中文(Chinese)名称', trigger: 'blur' }],
})
const gameSet = throttle(async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (!checkAmount(data.defaultList[0].num) && props.checkedItem.platform != '3' && !data.isPPshow) {
        return ElMessage.error('请同步修改默认投注金额')
      }
      if (data.pressureList[0].num > data.pressureList[1].num && data.isPPshow) {
        return ElMessage.error('设定的下限值不能大于上限值')
      }
      // 处理压注缩小倍数
      data.defaultList.forEach((item: any) => {
        item.num = BigTimes(item.num, data.client_balance_scale)
      })
      data.pressureList.forEach((item: any) => {
        item.num = BigTimes(item.num, data.client_balance_scale)
      })
      await editTiger(data, true);
      ElMessage.success('修改成功')
      emit('onHideDetails', true)
    }
  })
}, 3000)

// 设置PP自有游戏的压注金额
const ppAmount = () => {
  data.isPPshow = false
  if (!data.ppa_slots_amount) return
  data.isPPshow = true
  // 投注金额
  nextTick(async () => {
    let res = await getBetAmount({
      min_num: BigTimeWan(BigTimes(data.pressureList[0].num, data.client_balance_scale)),
      max_num: BigTimeWan(BigTimes(data.pressureList[1].num, data.client_balance_scale)),
      line_num: data.otherLine
    }), dataList = [] as any[];
    res.data?.forEach((item: any) => {
      dataList.push({ num: item })
    })
    data.pressurePPList = dataList
    // 默认投注金额
    data.defaultList[0].num = dataList[0].num
  })
}

// 爆奖倍数控制
const setArrMultipleControl = () => {
  let arr3 = [] as any[], maxPosition = data.multipleControl[data.multipleControl.length - 1].position, setPosition = data.bigControl[data.bigControl.length - 1].min;
  ppAmount()
  nextTick(() => {
    // 查询档位压注区间
    data.pressureList?.forEach((item: any) => {
      data.otherLevel?.forEach((second: any) => {
        arr3.push({ bet: BigTimes(second, BigTimes(item.num, data.otherLine)) })
      })
    })
    console.log('最大档位-', maxPosition, '设定档位-', setPosition, '压注区间', arr3);
    data.multipleControl?.forEach((item: any, index: number) => {
      item.show = false
      arr3?.forEach((second: any, two: number) => {
        if (index == two + 1) {
          item.bet = second.bet
          item.show = true
        }
      })
      // 设定档位大于最大档位处理-1档(如果小于则去除 -1档)
      if (setPosition >= maxPosition) {
        if (item.position == -1) {
          item.bet = arr3[data.multipleControl.length - 1].bet
          item.maxBet = arr3[arr3.length - 1].bet
          item.show = true
        }
      }
    })
  })
}

// 查询基础面额
const checkAmount = (num: number) => {
  if (data.pressureList.find((item: any) => item.num == num)) {
    return true
  } else {
    return false
  }
}

// 新增押注面额
const scrollContainer = ref<any>()
const addPressure = () => {
  if (data.pressureList.length > 14) {
    return ElMessage.error('最多只能配置15个')
  } else {
    data.pressureList.push({ num: 0.01 })
    scrollContainer.value.scrollLeft = 250 * data.pressureList.length
  }
}
// 减少押注面额
const reducePressure = (index: number) => {
  if (!index && data.pressureList.length == 1) {
    return ElMessage.error('最少保留一个押注面额！')
  }
  data.pressureList.splice(index, 1)
}

// 重置
const emit = defineEmits(['onHideDetails'])
const onHideDetails = () => {
  emit('onHideDetails', false)
}
</script>

<style scoped lang="scss">
.box-item {
  padding: 5px;
  background-color: #f8f8f8;
  border-radius: 5px;
}

.amountBox {
  overflow: auto;
  white-space: nowrap;

  /* 定义滚动条宽度和背景颜色 */
  &::-webkit-scrollbar {
    height: 6px;
    /* 定义滚动条宽度 */
  }
}
</style>